package com.is.servlet;

import java.security.MessageDigest;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;
/**
 * 
 * @author cYoung
 * @date 2012-10-07
 */
public class TokenProcessor {
    private TokenProcessor(){}
    private static final TokenProcessor instance = new TokenProcessor(); //单例模式,只使用一个对象
    public static TokenProcessor getInstance(){
	return instance;
    }
    
    /**
     * 产生令牌
     * @param request
     * @param response
     * @return
     */
    public static String generateToken(HttpServletRequest request,HttpServletResponse response){
	String token = System.currentTimeMillis()+new Random().nextInt()+"";
	try {
	    MessageDigest mDigest = MessageDigest.getInstance("md5"); //md5摘要，128字节，统一长度
	    byte[] md5 = mDigest.digest(token.getBytes()); //BASE64编码
	    BASE64Encoder encoder = new BASE64Encoder();
	    request.getSession().removeAttribute("token");
	    request.getSession().setAttribute("token", encoder.encode(md5));
	    System.out.println("生成："+encoder.encode(md5));
	    return encoder.encode(md5);
	} catch (Exception e) {
	    // TODO: handle exception
	    throw new RuntimeException(e);
	}
	
    }
   
    /**
     * 是否允许提交
     * true允许
     * @param request
     * @param client_token
     * @return
     */
    public static boolean AllowCommited(HttpServletRequest request,String client_token){
	 // String client_token = request.getParameter("token");
	  String serve_token = (String) request.getSession().getAttribute("token");
	  System.out.println("获取："+client_token);
	  boolean flag = false;
	  if(client_token.equals(serve_token)){
	      flag= true;
	      request.getSession().removeAttribute("token"); //使用一次后就销毁session
	  }
	  return flag;
  }

}
